package com.xpf.shardingtabledemo.dbqueryext;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDate;

/**
 * @Author xpf
 * @Date 2023/9/22 15:46
 * @Version 1.0
 */

@Component
@Slf4j
public class AutoCreateTableSchedule{

    public JdbcTemplate jdbcTemplate;

    @Autowired
    public AutoCreateTableSchedule(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @Scheduled(cron = "0 0 4 * * *")
    public void AutoCreateTable(){
        createCallingApiTable();
    }

    public void createCallingApiTable() {

        try {

            // 获取当前日期
            LocalDate currentDate = LocalDate.now();

            // 自动往后建6个月
            for (int i = 0; i < 6; i++) {
                LocalDate nextMonth = currentDate.plusMonths(i + 1);
                int monthValue = nextMonth.getMonthValue();
                int year = nextMonth.getYear();
                String formattedMonth = String.format("%02d", monthValue);
                String tableName = "operationPerson_log_" + year + "_" + formattedMonth;
                String sql = "CREATE TABLE IF NOT EXISTS tablename (" +
                        "`id` int(11) NOT NULL AUTO_INCREMENT,\n" +
                        "  `name` varchar(255) DEFAULT NULL,\n" +
                        "  `age` int(10) DEFAULT NULL,\n" +
                        "PRIMARY KEY (`id`)," +
                        "index idx_name(name)" +
                        ")";
                sql = sql.replace("tablename",tableName);

                jdbcTemplate.execute(sql);
            }
        } catch (Exception e) {
            log.error("create byd_operation_log error" + e.getMessage(), e);
        }
    }
}
